#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import math

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class GansuLongnanPolicy(BaseTaxPolicySpider):
    name = 'gansu_longnan_qu_policy'
    
    province = '甘肃省'
    city: str = "陇南市"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                "DOWNLOADER_MIDDLEWARES": {
                    # "scrapy.downloadermiddlewares.useragent.UserAgentMiddleware": None,  # 为 None 失效
                    "scrapy.downloadermiddlewares.retry.RetryMiddleware": None,  # 为 None 失效
                    "components.middlewares.downloadmiddlewares.public.useragent_random.RandomUserAgentMiddleware": 550,
                    "components.middlewares.downloadmiddlewares.public.company_ip_by_api.CompanyIpByApiMiddleware": 551,
                    "components.middlewares.downloadmiddlewares.public.error_collector.ErrorCollectorMiddleware": 552,
                    'components.middlewares.downloadmiddlewares.private.rs_6_middlewares.Rs6RetryMiddleware': 553,
                },
                "DOWNLOAD_TIMEOUT": 200,
                # 'CONCURRENT_REQUESTS': 1,
                "HTTPERROR_ALLOWED_CODES": [400, 404, 500, 200, 202, 502, 407],
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url, path in [
            ['西和县人民政府', "西和县", "https://www.xihe.gov.cn/zfxxgk/public/column/5664062?type=4&catId=12413162&action=list", "首页>信息公开首页>信息公开专题首页>西和县人民政府>政府文件>按公文文种分类>西政发"],
            ['西和县人民政府', "西和县", "https://www.xihe.gov.cn/zfxxgk/public/column/5664062?type=4&catId=12413163&action=list", "首页>信息公开首页>信息公开专题首页>西和县人民政府>政府文件>按公文文种分类>西政办发"],
            # ['西和县人民政府', "西和县", "https://www.xihe.gov.cn/zfxxgk/public/column/5664062?type=4&catId=12413643&action=list", "首页>信息公开首页>信息公开专题首页>西和县人民政府>政府文件>行政规范性文件"],
            ['两当县人民政府', "两当县", "https://www.ldxzf.gov.cn/zfxxgk/public/column/4663967?type=4&catId=8459069&action=list", "首页>信息公开首页>信息公开专题首页>两当县人民政府办公室>政府文件>按公文文种分类>两政办发"],
            ['文县人民政府', "文县", "https://www.lnwx.gov.cn/zfxxgk/public/column/32130683?type=4&catId=68722260&action=list", "首页>信息公开首页>信息公开专题首页>文县人民政府>政府文件>按公文文种分类>县政府办公室文件"],
            ['康县人民政府', "康县", "https://www.gskx.gov.cn/zfxxgk/public/column/32127990?type=4&catId=68721921&action=list", "首页>信息公开首页>信息公开专题首页>康县人民政府>履职依据>县政府文件"],
            ['康县人民政府', "康县", "https://www.gskx.gov.cn/zfxxgk/public/column/32127990?type=4&catId=68721942&action=list", "首页>信息公开首页>信息公开专题首页>康县人民政府>履职依据>县政府办公室文件"],
            ['康县人民政府', "康县", "https://www.gskx.gov.cn/zfxxgk/public/column/32127990?type=4&catId=68721924&action=list", "首页>信息公开首页>信息公开专题首页>康县人民政府>履职依据>规范性文件"],
            ['礼县人民政府', "礼县", "https://www.gslx.gov.cn/zfxxgk/public/column/32129604?type=4&catId=68718348&action=list", "首页>信息公开首页>信息公开专题首页>礼县人民政府>履职依据>规范性文件"],
            ['成县人民政府', "成县", "https://www.gscx.gov.cn/zfxxgk/public/column/32127978?type=4&catId=68719891&action=list", "首页>信息公开首页>信息公开专题首页>成县人民政府办公室>政策文件"],
            ['徽县人民政府', "徽县", "https://www.gshxzf.gov.cn/zfxxgk/public/column/32129260?type=4&catId=68721233&action=list", "首页>信息公开首页>信息公开专题首页>徽县人民政府办公室>政策文件"],
            ['徽县人民政府', "徽县", "https://www.gshxzf.gov.cn/zfxxgk/public/column/32129260?type=4&catId=68721245&action=list", "首页>信息公开首页>信息公开专题首页>徽县人民政府办公室>规范性文件"],

        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_content, meta={'item': item, 'path': path})

    def parse_content(self, response, **kwargs):
        meta = response.meta
        path = meta['path']
        siteId = response.xpath(".").re_first(r"siteId:\s*[\"']+(.*?)[\"']+")
        organId = response.xpath(".").re_first(r"organId:\s*[\"']+(.*?)[\"']+") or response.xpath(".").re_first(r"columnId:\s*[\"']+(.*?)[\"']+")
        catId = response.xpath(".").re_first(r"catId:\s*[\"']+(.*?)[\"']+")
        file = response.xpath(".").re_first(r"file:\s*[\"']+(.*?)[\"']+")
        # if catId == '103143629':
        #     catId = ''
        params = {
            "_": "0.1776864649070664",
            "labelName": "publicInfoList",
            "keyWords": "",
            "searchType": "",
            "startDate": "",
            "endDate": "",
            "cId": "",
            "siteId": siteId,
            "pageSize": "15",
            "pageIndex": "1",
            "type": "4",
            "action": "list",
            "organId": organId,
            "catId": catId,
            "isJson": "true"
        }
        if file and '政府文件' in path:
            params['file'] = file
        print(params)
        url = '/zfxxgk/site/label/8888?'
        meta['url'] = url
        meta['params'] = params
        yield response.follow(url + urlencode(params), callback=self.parse_list, meta=meta, dont_filter=True)

    def parse_list(self, response, **kwargs):
        # print(response.url)
        meta = response.meta
        prev_item = meta.get('item')
        elem_list = response.json()['data']
        print(len(elem_list), response.url)
        for elem in elem_list:
            item = Item()
            item['source_url'] = f"/zfxxgk/public/{elem['organId']}/{elem['contentId']}.html"
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['publishDate']
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        total_page = response.json()['pageCount']
        print(response.url, len(elem_list), total_page)
        if meta.get("is_next") is not False:
            meta.update({'item': prev_item, 'is_next': False})
            url = meta['url']
            for i in range(1, int(total_page) + 1):
                params = meta['params']
                params['pageIndex'] = i
                yield response.follow(url+urlencode(params), callback=self.parse_list, meta=meta)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        # item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl gansu_longnan_qu_policy".split())
